import { Router, Request, Response } from 'express'
import OpenAI from 'openai'
import { authenticateToken, rateLimiter } from '../middleware/auth'
import { aiFunctionRegistry } from '../services/aiFunctionRegistry'
import { taskContextProvider } from '../services/taskContextProvider'
import { taskExecutors } from '../services/taskFunctionExecutors'

const router = Router()

// 注册所有任务函数
taskExecutors.forEach(executor => {
  aiFunctionRegistry.register(executor)
})

// 所有聊天路由需要认证
router.use(authenticateToken)

// 增强版SSE流式聊天：POST /api/chat/enhanced-stream
router.post('/enhanced-stream', rateLimiter(20, 1), async (req: Request, res: Response) => {
  try {
    // 设置 SSE 头，增强跨域和缓存控制
    res.setHeader('Content-Type', 'text/event-stream')
    res.setHeader('Cache-Control', 'no-cache, no-transform')
    res.setHeader('Connection', 'keep-alive')
    res.setHeader('X-Accel-Buffering', 'no') // 禁用Nginx缓冲
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.setHeader('Access-Control-Allow-Headers', 'Cache-Control, Content-Type')
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
    
    // 确保立即刷新头部
    if (typeof res.flushHeaders === 'function') {
      res.flushHeaders()
    }

    // 创建一个可以被请求关闭时中断的控制器
    const abortController = new AbortController()
    let isClientConnected = true
    
    // 监听客户端断开连接
    req.on('close', () => {
      console.log('客户端断开连接')
      isClientConnected = false
      abortController.abort()
    })
    
    // 监听请求超时
    req.on('timeout', () => {
      console.log('请求超时')
      isClientConnected = false
      abortController.abort()
    })

    // 辅助函数：安全地写入SSE数据
    const safeWrite = (data: any) => {
      if (!isClientConnected) return false
      try {
        const success = res.write(`data: ${JSON.stringify(data)}\n\n`)
        return success
      } catch (e) {
        console.error('写入SSE数据失败:', e)
        return false
      }
    }

    const { messages, sessionId } = req.body
    const userId = (req as any).userId

    if (!messages || !Array.isArray(messages)) {
      safeWrite({ error: 'Messages array is required' })
      res.end()
      return
    }

    // 获取任务上下文
    const aiContext = await taskContextProvider.buildAIContext(userId, sessionId)
    
    // 构建系统提示
    const taskContext = taskContextProvider.formatTasksForAI(aiContext.currentTasks)
    const taskContextData = await taskContextProvider.getTaskContext(userId)
    const stats = taskContextProvider.formatStatsForAI(taskContextData.taskStats)
    
    const systemMessage = {
      role: 'system' as const,
      content: `你是AIDE智能任务管理助手。你可以帮助用户创建、更新、查询和管理任务。

你可以使用以下功能：
- 创建新任务 (create_task)
- 更新现有任务 (update_task) 
- 查询任务列表 (query_tasks)
- 完成任务 (complete_task)
- 删除任务 (delete_task)
- 获取任务统计 (get_task_stats)

请根据用户需求提供帮助，如果需要操作任务，请使用相应的功能。回答要简洁明了。`
    }

    // 验证和清理消息
    const cleanMessages = messages.map(msg => ({
      role: msg.role,
      content: msg.content?.substring(0, 4000) || '' // 限制消息长度
    })).filter(msg => msg.content.trim().length > 0)

    const allMessages = [systemMessage, ...cleanMessages]

    // 验证消息格式
    if (allMessages.length === 0) {
      throw new Error('没有有效的消息')
    }

    const openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
      baseURL: process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1'
    })

    try {
      // 使用最新的 runTools 方法，增强错误处理和消息追踪
      try {
        // 使用请求中提供的会话ID或生成新的ID来跟踪当前对话
        const messageId = req.body.messageId || Date.now().toString()
        console.log(`继续/开始对话流: ${messageId}`)

        // 使用OpenAI v5.17.0版本的流式API
        try {
          const stream = await openai.chat.completions.create({
            model: process.env.OPENAI_MODEL || 'gpt-3.5-turbo',
            messages: allMessages,
            tools: aiFunctionRegistry.getToolDefinitions(userId),
            tool_choice: 'auto',
            temperature: 0.7,
            max_tokens: 1000,
            stream: true
          }, {
            signal: abortController.signal
          });

          // 处理流式响应
          for await (const chunk of stream) {
            if (abortController.signal.aborted) break;
            
            // 处理内容增量
            if (chunk.choices[0]?.delta?.content) {
              const content = chunk.choices[0].delta.content;
              console.log(`[${messageId}] Content delta:`, content);
              safeWrite({ delta: content, messageId });
            }
            
            // 处理工具调用 - 简化版本
            if (chunk.choices[0]?.delta?.tool_calls) {
              const toolCalls = chunk.choices[0].delta.tool_calls;
              
              for (const toolCall of toolCalls) {
                // 发送工具调用信息给前端
                if (toolCall.function?.name) {
                  console.log(`[${messageId}] Tool call:`, toolCall.function.name);
                  safeWrite({ 
                    functionCall: {
                      name: toolCall.function.name,
                      arguments: toolCall.function.arguments || '{}',
                      messageId
                    }
                  });
                }
              }
            }
            
            // 检查是否完成
            if (chunk.choices[0]?.finish_reason === 'stop') {
              console.log(`[${messageId}] Stream completed`);
              safeWrite({ final: true, messageId });
            }
          }
        } catch (streamError) {
          console.error(`[${messageId}] Stream error:`, streamError);
          safeWrite({ 
            error: streamError instanceof Error ? streamError.message : 'Stream failed',
            messageId
          });
        }
      } catch (runnerError) {
        console.error('Runner creation error:', runnerError)
        safeWrite({ 
          error: `AI处理错误: ${runnerError instanceof Error ? runnerError.message : '未知错误'}` 
        })
      }

    } catch (openaiError: any) {
      console.error('OpenAI API error:', openaiError)
      safeWrite({ 
        error: `OpenAI API错误: ${openaiError.message || '未知错误'}` 
      })
      res.end()
      return
    }

  } catch (error: any) {
    if (error.name === 'AbortError') {
      res.end()
      return
    }
    
    console.error('Enhanced chat stream error:', error)
    // 在外层作用域中没有safeWrite函数，直接使用res.write
    res.write(`data: ${JSON.stringify({ error: error.message || 'Stream failed' })}\n\n`)
    res.end()
  }
})

// 获取可用函数列表：GET /api/chat/functions
router.get('/functions', async (req: Request, res: Response) => {
  try {
    const functions = aiFunctionRegistry.getFunctionDefinitions()
    res.json({ functions })
  } catch (error: any) {
    res.status(500).json({ error: error.message })
  }
})

// 测试函数调用：POST /api/chat/test-function
router.post('/test-function', async (req: Request, res: Response) => {
  try {
    const { functionName, args } = req.body
    const userId = (req as any).userId
    
    const aiContext = await taskContextProvider.buildAIContext(userId)
    const result = await aiFunctionRegistry.executeFunction(functionName, args, aiContext)
    
    res.json(result)
  } catch (error: any) {
    res.status(500).json({ error: error.message })
  }
})

export default router
